package com.iretailer.report.web;

import com.iretailer.report.common.InternationalMessage;
import com.iretailer.report.service.UserService;
import com.iretailer.report.util.JsonUtil;
import com.iretailer.report.util.RMap;
import com.iretailer.report.util.SecurityUserUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.Base64;

/**
 * @program: report
 * @description:
 * @author: Bennie
 * @create: 2020-09-25 10:59
 **/


public class ReportAuthenticationFilter extends UserFilter {

    /**
     * 过滤方法
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object object) throws AuthenticationException {
        if (isLoginRequest(request, response) || getSubject(request, response).getPrincipal() != null) {
            return true;
        }
        String basic = "Basic ";
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String authorization = servletRequest.getHeader("Authorization");
        if (StringUtils.isNotEmpty(authorization) && authorization.startsWith(basic)) {
            String auth = new String(Base64.getDecoder().decode(authorization.substring(basic.length())), StandardCharsets.UTF_8);
            int index = auth.indexOf(":");
            if (index > 0) {
                String username = auth.substring(0, index);
                String password = auth.substring(index + 1);
                try {
                    String userName = MessageFormat.format("{0}{1}{2}", false, UserService.companyUserSplit, username);
                    UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
                    SecurityManager securityManager = SecurityUtils.getSecurityManager();
                    Subject subject = securityManager.login(getSubject(request, response), token);
                    HttpSession session = servletRequest.getSession();
                    Object principal = subject.getPrincipal();
                    session.setAttribute("user", principal);
                    return true;
                } catch (AuthenticationException e) {
                    //token 错误
                    e.printStackTrace();
                    responseOutWithJson(response, JsonUtil.bean2json(RMap.error(InternationalMessage.USER_NAME_OR_PASSWORD_ERROR.getByLanguage(SecurityUserUtil.defaultLanguage()))));
                }

            }

        }
        return false;
    }

    /**
     * 以JSON格式输出
     *
     * @param response
     */
    protected void responseOutWithJson(ServletResponse response, Object responseObject) {
        //将实体对象转换为JSON Object转换
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = httpServletResponse.getWriter();
            out.append((String) responseObject);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }


}
